package com.yili.printer.service;

import com.zebra.sdk.comm.Connection;
import com.zebra.sdk.comm.ConnectionException;
import com.zebra.sdk.comm.TcpConnection;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 斑马ZT411打印机核心类
 * 负责与斑马ZT411打印机的直接通信
 */
@Service
public class ZebraPrinter {

    private final Logger logger = LogManager.getLogger(ZebraPrinter.class);

    @Value("${printer.ip}")
    private String ip;

    @Value("${printer.port}")
    private int port;

    /**
     * 打印机连接状态
     */
    private boolean connected;

    private Connection printerConnection;

    /**
     * 打印机设备信息
     */
    private String deviceInfo;

    /**
     * 连接打印机
     *
     * @throws ConnectionException 连接异常
     */
    public void connect() throws ConnectionException {
        logger.info("开始连接打印机 {}:{}", ip, port);
        try {
            // 为指定地址的 ZPL TCP 端口实例化连接
            printerConnection = new TcpConnection(ip, port);
            printerConnection.open();

            // 获取打印机信息
            deviceInfo = printerConnection.getSimpleConnectionName();
            logger.info("打印机连接成功");
        } catch (ConnectionException e) {
            logger.error("打印机连接失败: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("打印机连接失败", e);
            throw new ConnectionException("连接打印机时发生未知错误: " + e.getMessage(), e);
        }
    }

    /**
     * 获取打印机连接状态
     *
     * @return 连接状态
     * @throws ConnectionException
     */
    public boolean isConnected() throws ConnectionException {
        logger.debug("检查打印机连接状态");
        connected = this.printerConnection.isConnected();
        logger.info("打印机连接状态: " + connected);
        return connected;
    }

    /**
     * 断开打印机连接
     *
     * @throws ConnectionException 连接异常
     */
    public void disconnect() throws ConnectionException {
        logger.info("开始断开打印机连接");
        try {
            if (printerConnection != null) {
                printerConnection.close();
            }
            logger.info("打印机连接已断开");
        } catch (ConnectionException e) {
            logger.error("断开打印机连接失败: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("断开打印机连接失败", e);
            throw new ConnectionException("断开打印机连接时发生未知错误: " + e.getMessage(), e);
        }
    }

    /**
     * 发送打印数据到打印机
     *
     * @param printData 打印数据
     * @throws ConnectionException 连接异常
     * @throws IllegalArgumentException 参数异常
     */
    public void sendPrintData(String printData) throws ConnectionException {
        logger.info("开始发送打印数据，数据长度: " + (printData != null ? printData.length() : 0));
        logger.debug("打印数据内容: " + printData);
        
        if (printData == null) {
            logger.error("打印数据为空");
            throw new IllegalArgumentException("打印数据不能为空");
        }
        
        if (!this.isConnected()) {
            logger.error("打印机未连接，无法发送打印数据");
            throw new ConnectionException("打印机未连接");
        }
        
        try {
            printerConnection.write(printData.getBytes());
            logger.info("打印数据发送成功");
        } catch (ConnectionException e) {
            logger.error("发送打印数据失败: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("发送打印数据失败", e);
            throw new ConnectionException("发送打印数据时发生未知错误: " + e.getMessage(), e);
        }
    }

    /**
     * 获取打印机设备信息
     *
     * @return 设备信息
     */
    public String getDeviceInfo() {

        return deviceInfo;
    }
}